//
//  ShareViewController.m
//  YTwallet
//
//  Created by hadrlog on 2019/2/22.
//  Copyright © 2019年 hadrlog. All rights reserved.
//

#import "ShareViewController.h"
#import "shareView.h"
#import "MyTeamViewController.h"
#import "WXApi.h"
#import "LoginViewController.h"
#import "NavigateViewController.h"
#import "ShareEarnView.h"
#import "ShareQRCodeModelPack.h"
//系统生成二维码
#import <CoreImage/CoreImage.h>

@interface ShareViewController ()<WXApiDelegate>
@property(nonatomic,strong)shareView *sv;
@property(nonatomic,strong)ShareEarnView *shareEarnView;

//后端返回的图片数据Data
@property(nonatomic,strong)NSData *imageData;


@end

@implementation ShareViewController

-(void)loadView
{
    [super loadView];
    self.sv = [[shareView alloc] initWithFrame:self.view.bounds];
    self.view = self.sv;
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    //展示推荐总人数、邀请码和二维码
    NSString *totalCount = [AppTools shareInstance].userInfo.recomendNum;
    NSString *inviteCode = [AppTools shareInstance].userInfo.userId;
    if (totalCount == nil || totalCount.length == 0) {
        totalCount = @"0";
    }
    self.sv.totalNumLab.text = [NSString stringWithFormat:@"%@%@",totalCount,@"人"];
    self.sv.inviteCodeNumLab.text = inviteCode;
    [self createCIQRCod];
    
}

-(void)createCIQRCod
{
    
    // 1.创建过滤器 -- 苹果没有将这个字符封装成常量
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    
    // 2.过滤器恢复默认设置
    [filter setDefaults];
    
    // 3.给过滤器添加数据(正则表达式/帐号和密码) -- 通过KVC设置过滤器,只能设置NSData类型
    NSString *dataString = [AppTools shareInstance].userInfo.shareUrl;
    NSData *data = [dataString dataUsingEncoding:NSUTF8StringEncoding];
    [filter setValue:data forKeyPath:@"inputMessage"];
    
    // 4.获取输出的二维码
    CIImage *outputImage = [filter outputImage];
    
    // 5.显示二维码
    self.sv.QRcodeImv.image = [self createNonInterpolatedUIImageFormCIImage:outputImage withSize:148];
}


/**
 *  根据CIImage生成指定大小的UIImage
 *
 *  @param image CIImage
 *  @param size  图片宽度
 */
- (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat) size
{
    CGRect extent = CGRectIntegral(image.extent);
    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
    
    // 1.创建bitmap;
    size_t width = CGRectGetWidth(extent) * scale;
    size_t height = CGRectGetHeight(extent) * scale;
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    CGContextScaleCTM(bitmapRef, scale, scale);
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    
    // 2.保存bitmap到图片
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    CGContextRelease(bitmapRef);
    CGImageRelease(bitmapImage);
    
    
    
    
    UIImage *showImage = [UIImage imageWithCGImage:scaledImage];
    
    
    //开启绘图,获取图形上下文  (上下文的大小,就是二维码的大小)
//    UIGraphicsBeginImageContext(showImage.size);
    //解决小图标添加模糊问题
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(showImage.size.width, showImage.size.height), NO,[UIScreen mainScreen].scale);
    
    //把二维码图片画上去. (这里是以,图形上下文,左上角为 (0,0)点)
    [showImage drawInRect:CGRectMake(0, 0, showImage.size.width, showImage.size.height)];
    //再把小图片画上去
    UIImage *sImage = [UIImage imageNamed:@"MYicon"];
    
    CGFloat sImageW = 30;
    CGFloat sImageH= sImageW;
    CGFloat sImageX = (showImage.size.width - sImageW) * 0.5;
    CGFloat sImgaeY = (showImage.size.height - sImageH) * 0.5;
    
    [sImage drawInRect:CGRectMake(sImageX, sImgaeY, sImageW, sImageH)];
    
    //获取当前画得的这张图片
    UIImage *finalyImage = UIGraphicsGetImageFromCurrentImageContext();
    
    
    
    
    //关闭图形上下文
    UIGraphicsEndImageContext();
    
    return finalyImage;
}



- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.sv.nameLab.text = [AppTools shareInstance].userInfo.userName;
    
    [self.sv.myTeamBtn addTarget:self action:@selector(myTeamBtnAction) forControlEvents:(UIControlEventTouchUpInside)];
    
    self.sv.arrowImv.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(myTeamBtnAction)];
    [self.sv.arrowImv addGestureRecognizer:tap];
    
    
    [self.sv.CCopyBtn addTarget:self action:@selector(CCopyBtnAction) forControlEvents:(UIControlEventTouchUpInside)];
    
    [self.sv.sharebtn addTarget:self action:@selector(sharebtnAction) forControlEvents:(UIControlEventTouchUpInside)];
    
}
-(void)myTeamBtnAction
{
    NSLog(@"点击我的团队");
    MyTeamViewController *MyTeamView = [[MyTeamViewController alloc] init];
    [self.navigationController pushViewController:MyTeamView animated:YES];
}

-(void)CCopyBtnAction
{
    NSLog(@"点击复制");
    if (self.sv.inviteCodeNumLab.text.length > 0) {
        [self showSuccessResultTips:@"复制成功" animated:YES forSeconds:SUCCESS_SHOW_TIME_DEF
                    completionBlock:^{
                        UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
                        pasteboard.string = self.sv.inviteCodeNumLab.text;
                    }];
        
    }
    
    
}

-(void)sharebtnAction
{
    NSLog(@"点击分享赚收益");
    
    
    if ([AppTools checkLoginResponseAllState] == ETNOAutonym) {
        [self showFailedResultTips:@"请先实名认证" animated:YES forSeconds:FAIL_SHOW_TIME_DEF];
        return;
    }
    
    
    NSString *url = [[ServerAddressModel shareInstance] fullTAnd0AddrWithParameter:@"/epay_apps/qrCode/shareQrCode"];
    [[ETONEHttpClient sharedInstance] doHTTPSPOST:url Parameters:nil HttpBody:nil SuccessHandler:^(id responseObject) {
        
        NSDictionary *dic = [responseObject mj_JSONObject];
        NSString *code = dic[@"code"];
        if ([@"0000" isEqualToString:code]) {
            [self dealShareQRCode:responseObject];
        }
        
    } FailedHandler:^(NSError *error) {
        
    }];
    
}

-(void)dealShareQRCode:(id)responseObject
{
    self.shareEarnView = [[ShareEarnView alloc] initWithFrame:[UIApplication sharedApplication].keyWindow.bounds];
    [[UIApplication sharedApplication].keyWindow addSubview:self.shareEarnView];
    
    [self.shareEarnView.cancleBtn addTarget:self action:@selector(cancleBtnAction) forControlEvents:(UIControlEventTouchUpInside)];
    
    
    [self.shareEarnView.offBtn addTarget:self action:@selector(cancleBtnAction) forControlEvents:(UIControlEventTouchUpInside)];
    
    
    ShareQRResponse *shareQRResponse = [ShareQRResponse mj_objectWithKeyValues:responseObject];
    NSData *data = [[NSData alloc] initWithBase64EncodedString:shareQRResponse.response.base64img options:(NSDataBase64DecodingIgnoreUnknownCharacters)];
    self.imageData = data;
    UIImage *image = [UIImage imageWithData:self.imageData];
    self.shareEarnView.midView.layer.contents = (id)image.CGImage;
    
    //微信好友点击事件
    [self.shareEarnView.weChatFriendBtn addTarget:self action:@selector(weChatFriendBtnAction) forControlEvents:(UIControlEventTouchUpInside)];
    //微信朋友圈点击事件
    [self.shareEarnView.circleOfFriendsBtn addTarget:self action:@selector(circleOfFriendsBtnAction) forControlEvents:(UIControlEventTouchUpInside)];
    //保存图片
    [self.shareEarnView.saveImageBtn addTarget:self action:@selector(saveImageBtnAction) forControlEvents:(UIControlEventTouchUpInside)];
    
}
-(void)weChatFriendBtnAction
{
    
    NSLog(@"点击微信好友");
   
    
    WXImageObject *imageObject = [WXImageObject object];
    imageObject.imageData = self.imageData;
    
    WXMediaMessage *message = [WXMediaMessage message];
    message.mediaObject = imageObject;
    
    SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
    req.bText = NO;
    req.message = message;
    req.scene = WXSceneSession;
    [WXApi sendReq:req];
//    [self showFailedResultTips:ETNODisparkStr animated:YES forSeconds:FAIL_SHOW_TIME_DEF];
}
-(void)circleOfFriendsBtnAction
{
    WXImageObject *imageObject = [WXImageObject object];
    imageObject.imageData = self.imageData;
    
    WXMediaMessage *message = [WXMediaMessage message];
    
    message.mediaObject = imageObject;
    
    SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
    req.bText = NO;
    req.message = message;
    req.scene = WXSceneTimeline;
    [WXApi sendReq:req];
    NSLog(@"点击微信朋友圈");
    [self showFailedResultTips:ETNODisparkStr animated:YES forSeconds:FAIL_SHOW_TIME_DEF];
}
-(void)saveImageBtnAction
{
    NSLog(@"点击保存图片");
    UIImage *image = [UIImage imageWithData:self.imageData];
    [self loadImageFinished:image];
    
}

- (void)loadImageFinished:(UIImage *)image
{
    UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), (__bridge void *)self);
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    if (error) {
        NSLog(@"%@",error.localizedDescription);
        [self showFailedResultTips:error.localizedDescription animated:YES forSeconds:FAIL_SHOW_TIME_DEF];
    }else
    {
        NSLog(@"保存成功");
        [self showSuccessResultTips:@"保存成功" animated:YES forSeconds:SUCCESS_SHOW_TIME_DEF];
    }
    
    NSLog(@"image = %@, error = %@, contextInfo = %@", image, error, contextInfo);
}

-(void)cancleBtnAction
{
    [self.shareEarnView removeFromSuperview];
}

@end
